package com.example.demo2.controller;

import com.example.demo2.entity.Program;
import com.example.demo2.mapper.ProgramMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/program")
@CrossOrigin
public class ProgramController {

    @Autowired
    private ProgramMapper programMapper;

    private static final String SERVER_UPLOAD_DIR = "D:\\file\\pdf";
    private static final String FILE_ACCESS_PATH = "/file/pdf/";

    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> uploadPDF(@RequestParam("file")  MultipartFile file){
        try {
            System.out.println("sadasdasdadds");
            String originalFilename = file.getOriginalFilename();
            String filename = UUID.randomUUID().toString() +
                    originalFilename.substring(originalFilename.lastIndexOf("."));

            Path path = Paths.get(SERVER_UPLOAD_DIR, filename);
            Files.createDirectories(path.getParent());

            Files.write(path, file.getBytes());
            Map<String, Object> data = new HashMap<>();
            data.put("url", FILE_ACCESS_PATH + filename);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("data", data);
            response.put("message", "success");
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getProgramsByPjId(@RequestParam("pjId") Integer pjId) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<Program> programs = programMapper.findProgramByPjId(pjId,"操作规程");
            response.put("code", 200);
            response.put("data", programs);
            response.put("message", "success");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            response.put("code", 500);
            response.put("message", "获取规程列表失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    @PostMapping("/add1")
    public ResponseEntity<Map<String, Object>> addProgram(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 检查必要参数
            String pgName = (String) request.get("pgName");
            String pgUrl = (String) request.get("pgUrl");
            Integer pjId = Integer.valueOf(String.valueOf(request.get("pjId")));
            //program.setPgName(String.valueOf(request.get("pgName")));
            if (pgName == null || pgUrl == null || pjId == null) {
                response.put("code", 400);
                response.put("message", "缺少必要参数");
                return ResponseEntity.badRequest().body(response);
            }

            Program program = new Program();
            program.setPgName(pgName);
            program.setPgUrl(pgUrl);
            program.setPgType("操作规程");
            program.setPjId(pjId);
            program.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

            // 打印日志
            System.out.println("Adding program: " + program);

            int result = programMapper.insertProgram(program);
            if (result > 0) {
                response.put("code", 200);
                response.put("message", "添加成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("code", 500);
                response.put("message", "添加失败");
                return ResponseEntity.status(500).body(response);
            }



        } catch (Exception e) {
            e.printStackTrace();
            response.put("code", 500);
            response.put("message", "添加失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
    @PutMapping("/update/pgId/{pgId}")
    public ResponseEntity<Map<String, Object>> updateProgram(
            @PathVariable("pgId") Integer pgId,
            @RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            Program existingProgram = programMapper.selectProgramById(pgId);
            if (existingProgram == null) {
                response.put("code", 404);
                response.put("message", "规程不存在");
                return ResponseEntity.status(404).body(response);
            }

            // 更新记录
            Program program = new Program();
            program.setPgId(pgId);
            program.setPgName(String.valueOf(request.get("pgName")));

            program.setPgUrl((String) request.get("pgUrl"));
            program.setPgType("操作规程");
            program.setPjId(Integer.valueOf(String.valueOf(request.get("pjId"))));

            // 使用正确的日期格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            program.setUpdateTime(sdf.format(new Date()));

            int result = programMapper.updateProgram(program);
            if (result > 0) {
                response.put("code", 200);
                response.put("message", "更新成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("code", 500);
                response.put("message", "更新失败");
                return ResponseEntity.status(500).body(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.put("code", 500);
            response.put("message", "更新失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    @DeleteMapping("/delete/{pgId}")
    public ResponseEntity<Map<String, Object>> deleteProgram(@PathVariable("pgId") Integer pgId) {
        Map<String, Object> response = new HashMap<>();
        try {
            Program program = programMapper.selectProgramById(pgId);
            if (program == null) {
                response.put("code", 404);
                response.put("message", "规程不存在");
                return ResponseEntity.status(404).body(response);
            }

            if (program.getPgUrl() != null) {
                String filePath = SERVER_UPLOAD_DIR + program.getPgUrl().substring(program.getPgUrl().lastIndexOf("/"));
                Files.deleteIfExists(Paths.get(filePath));
            }

            programMapper.deleteProgram(pgId);

            response.put("code", 200);
            response.put("message", "删除成功");
            return ResponseEntity.ok(response);
        }
        catch (Exception e) {
            response.put("code", 500);
            response.put("message", "删除失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }

    }
}